/**
 * Created by qunxing.du on 2016/7/18.
 * Copyright 2016 汉威.智慧环保事业部 Limited.
 * All rights reserved.
 */
package com.hw.one.collect.gdyc.job;

import com.alibaba.fastjson.JSON;
import com.hw.one.collect.gdyc.GdClient;
import com.hw.one.collect.gdyc.memento.GdycCareTaker;
import com.hw.one.collect.gdyc.memento.GdycMemento;
import com.hw.one.collect.gdyc.memento.GdycOriginator;
import com.hw.one.collect.job.Job;
import com.hw.one.collect.util.HashUtil;
import org.apache.log4j.Logger;

import java.util.Map;

/**
 * 广德扬尘job
 */
public abstract class AbstractGdJob extends Job{
    private static Logger log = Logger.getLogger(AbstractGdJob.class);
    protected static int GD_RAW_FIVEMIN_INTERVAL = 30;//分
    protected static int GD_FIVEMIN_FAULT_TOLERANT_INTERVAL = 10;//分

    /**
     * 推送数据
     * @param data
     */
    public synchronized void push(String data,String startDate,String endDate){
        try{
            //创建备忘录
            createMemento(startDate,endDate);
            if(data != null && !data.isEmpty()){
                log.info("推送开始，待发送数据："+ data);
                String result =  GdClient.send(data);

//                Object[] res = GdClient.getInstance().invoke("saveYCJC", data);
//                String result = (String) res[0];
                log.info("推送结果：" + result);
                Map<String,String> resultMap = JSON.parseObject(result,Map.class);
                if("0".equals(resultMap.get("true"))){
                    //移除备忘录
                    removeMemento(startDate,endDate);
                }else {
                    //更新备忘录
                    updateMemento(startDate,endDate);
                }
            }else {
                log.info("不推送,待发送数据为空");
                //更新备忘录
                updateMemento(startDate,endDate);
            }
        }catch (Exception e){
            //更新备忘录
            updateMemento(startDate,endDate);
            log.error("广德数据推送异常",e);
        }
    }
    protected void createMemento(String startTime,String endTime){
        GdycOriginator gdycOriginator = new GdycOriginator(startTime,endTime,0);
        GdycMemento memento = gdycOriginator.createMemento();
        GdycCareTaker.newInstance().saveOrUpdate(HashUtil.hashCode(startTime+endTime),memento);
        log.debug("创建广德备忘录");
    }

    protected void updateMemento(String startTime,String endTime){
        Integer key = HashUtil.hashCode(startTime+endTime);
        GdycMemento memento = GdycCareTaker.newInstance().get(key);
        if(memento != null){
            GdycCareTaker.newInstance().update(key,memento);
        }
        log.debug("修改广德备忘录");
    }

    protected void removeMemento(String startTime,String endTime){
        GdycCareTaker.newInstance().remove(HashUtil.hashCode(startTime+endTime));
        log.debug("移除广德备忘录");
    }
}
